package com.netease.examination.service;

import com.alibaba.fastjson.JSONObject;
import com.netease.examination.util.ExaminationUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * designed by destiny
 *
 * @author destiny
 *         e-mail destinywk@163.com
 *         github https://github.com/DestinyWang
 *         oschina https://git.oschina.net/destinywk
 * @version JDK 1.8.0_101
 * @since 2017/3/30 12:02
 */
@Service
public class QiniuService {

    private static final Logger logger = LoggerFactory.getLogger(QiniuService.class);

    // 设置好账号的ACCESS_KEY和SECRET_KEY
    private final String ACCESS_KEY = "xb49kERp5PGpZc-Qgy3c-_yj52v72PgNno5wn-s3";
    private final String SECRET_KEY = "i-eSKbSsEYt5i5n86ImEftfE-Nw0r4l91vDw9SDT";
    // 要上传的空间
    private final String bucketName = "destiny";


    // 密钥配置
    private Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    // 创建上传对象
    private UploadManager uploadManager = new UploadManager();

    // 简单上传，使用默认策略，只需要设置上传的空间名就可以了
    private String getUpToken(){
        return auth.uploadToken(bucketName);
    }

    public String saveImageByFile(MultipartFile file) throws IOException {
        System.out.println("QiniuService.saveImage");
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            if (!ExaminationUtil.isFileAllowed(fileExt)) {
                return null;
            }
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            // 打印返回的信息
//            System.out.println(res.bodyString());
            // {"hash":"Fp1G1G5d-dNSZTGPnS_4H-5zvSY-","key":"3dcc73ac3148402397f0cc97bc82a14b.jpg"}
            logger.info(res.toString());
            if (res.isOK() && res.isJson()) {
                String key = JSONObject.parseObject(res.bodyString()).get("key").toString();
                return ExaminationUtil.QINIU_DOMAIN + key;
            } else {
                logger.error("七牛文件上传错误：" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            logger.error("七牛文件上传错误：" + e.getMessage());
            return null;
        }
    }

    public void downloadImage() {

    }

}
